﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HandyControl.Controls;
using HandyControl.Tools;
using HandyControl.Data;
using MyHelper;
using System.Windows.Media.Animation;
using System.Timers;
using System.Windows.Interop;
using System.Diagnostics;
using System.Threading;
using Color = System.Windows.Media.Color;

namespace weighing
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : GlowWindow
    {

        #region variables area
        /// <summary>
        /// 视频区域的用户控件
        /// </summary>
        public VideoContent VideoContent { get; set; }

        private string _growlKey = "";
        public string GrowlKey
        {
            get
            {
                if (string.IsNullOrEmpty(_growlKey))
                {
                    var token = Growl.GetToken(this.GrowlPanel);
                    _growlKey = token ?? "main";
                }
                return _growlKey;
            }
        }
        #endregion

        public MainWindow()
        {
            InitializeComponent();

            //this.CommandBindings.Add(ViewMenuItemCommand.commandBinding);

            App.Current.MainWindow = this;

            CommonFunction.ShowCustomIcon(this);

            SetWindowTitle();
            //窗口主菜单
            NonClientAreaContent = new NoUserContent();

            ReLayoutWeighingUI();
        }

        #region windown event
        private void MainWiondow_Loaded(object sender, RoutedEventArgs e)
        {
            App.IsLogOut = false;

            if (App.Config.UserConfig.ShowVideoArea == false)
            {
                Task.Delay(1000).ContinueWith((t) =>
                {
                    this.Dispatcher.Invoke(async () =>
                    {
                        this.Width++;
                        await Task.Delay(100);
                        this.Width--;
                    });
                });
            }

            DelegeteFactory.Instance.OnWeighingWeighingModeChanged += OnWeighingWeighingModeChanged;
        }
        private void OnWeighingWeighingModeChanged(WeighingMode mode)
        {
            ReLayoutWeighingUI();
        }
        private void MainWiondow_ContentRendered(object sender, EventArgs e)
        {
            this.mainNotifyIcon.Visibility = Visibility.Visible;

            CommonFunction.ShowCustomNotiflyIco(mainNotifyIcon);

            this.copyrightTB.Text = App.Config.SystemConfig.CopyRight;

            ShowOrHideVideo(false);

            SyncNoActiveLimits();

        }
        private void MainWiondow_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.T && e.KeyboardDevice.Modifiers == ModifierKeys.Control)
            {

            }
        }

        private void MainWiondow_SizeChanged(object sender, SizeChangedEventArgs e)
        {

        }

        private void MainWiondow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (App.IsLogOut)
            {
                this.mainNotifyIcon.Visibility = Visibility.Collapsed;
                this.mainNotifyIcon.Dispose();
            }
            else
            {
                if (this.mainNotifyIcon.Visibility == Visibility.Visible)
                {
                    this.Hide();
                    HandyControl.Controls.NotifyIcon.ShowBalloonTip("提示", "系统被藏在这里了", NotifyIconInfoType.None, this.mainNotifyIcon.Token);
                    e.Cancel = true;
                }
                else
                {
                    App.Current.Shutdown();
                }
            }
        }

        private void MainWiondow_Closed(object sender, EventArgs e)
        {
            DelegeteFactory.Instance.OnWeighingWeighingModeChanged -= OnWeighingWeighingModeChanged;
        }
        #endregion 

        /// <summary>
        /// Show Or Hide Video
        /// </summary>
        /// <param name="isclickMi">是否点击了 系统菜单</param>
        public void ShowOrHideVideo(bool isclickMi)
        {
            if (App.Config.UserConfig.ShowVideoArea)
            {
                this.videoBorder.Visibility = Visibility.Visible;
                if (this.VideoContent == null)
                {
                    this.VideoContent = new VideoContent();
                    this.videoBorder.Child = this.VideoContent;
                }
                else
                {
                    this.VideoContent.Visibility = Visibility.Visible;
                    this.VideoContent.PreviewCamera();
                }
            }
            else
            {
                this.videoBorder.Visibility = Visibility.Collapsed;

                this.VideoContent?.StorpPreviewCamera();
            }
            if (isclickMi)
            {
                if (this.WeighingUIBorder.Child is NomalWeighingUc uc)
                {
                    uc.ReLayout();

                    Task.Delay(1000).ContinueWith(t =>
                    {
                        this.Dispatcher.Invoke(async () =>
                        {
                            this.Width++;
                            await Task.Delay(100);
                            this.Width--;
                        });
                    });
                }
            }
        }
        /// <summary>
        /// 设置系统名称
        /// </summary>
        private void SetWindowTitle()
        {
            string sysName = App.Config.SystemConfig.SystemName;
            if (string.IsNullOrEmpty(sysName))
            {
                sysName = "称重系统";
            }
            if (App.initConfig?.ActiveType == ActiveType.Code)
            {
                if (!ActiveCodeHelper.IsSoftActive())
                {
                    sysName += " 试用版";
                }
            }
            else
            {
                if (!ActiveDongleHelper.IsActived())
                {
                    sysName += " 试用版";
                }
            }


            this.Title = sysName;
        }



        #region status Bar
        /// <summary>
        /// 警告信息提示（一直提示）
        /// </summary>
        /// <param name="message">提示信息</param>
        private void Alert(string message)
        {
            // #FF68217A
            this.mainStatusBar.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0x21, 0x2A));
            //AlertBarItemTb.Text = message;
        }

        /// <summary>
        /// 普通状态信息提示
        /// </summary>
        /// <param name="message">提示信息</param>
        private void Information(string message)
        {
            this.mainStatusBar.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0x00, 0x7a, 0xcc));
            //AlertBarItemTb.Text = message;
        }

        /// <summary>
        /// 警告状态信息提示
        /// </summary>
        /// <param name="message">提示信息</param>
        private void Warning(string message)
        {
            // #FFCA5100 警告
            this.mainStatusBar.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xCA, 0x51, 0x00));
            //AlertBarItemTb.Text = message;
        }

        #endregion



        /// <summary>
        /// 同步限止次数
        /// </summary>
        public void SyncNoActiveLimits()
        {
            int rows = WeighingBillDao.Instance.Count();
            App.NoActiveLimits = rows;
        }

        //过期提示
        private void SoftExpiredSBI_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            new AboutWindow() { Owner = this }.Show();
        }


        private void RefreshScaleMI_Click(object sender, RoutedEventArgs e)
        {
            this.ScaleContentUc.RefreshHi_Click(sender, e);
        }

        private void RefreshVidoeContentMi_Click(object sender, RoutedEventArgs e)
        {
            this.VideoContent.ReFresh_MI_Click(sender, e);
        }

        /// <summary>
        /// 重先布局界面
        /// </summary>
        public void ReLayoutWeighingUI()
        {
            var tempMode = App.Config.WeighingConfig.WeighingMode;
            if (tempMode == WeighingMode.Standard)
            {
                if (this.WeighingUIBorder.Child != null)
                {
                    if (!(this.WeighingUIBorder.Child is NomalWeighingUc nomalUi))
                    {
                        //UI不对
                        this.WeighingUIBorder.Child = null;
                    }
                    else
                    {
                        //改变界面布局
                    }
                }

                if (this.WeighingUIBorder.Child == null)
                {
                    var ui = new NomalWeighingUc();
                    this.WeighingUIBorder.Child = ui;
                    ui.ReLayout();
                }
            }
            else if (tempMode == WeighingMode.Simple)
            {
                if (this.WeighingUIBorder.Child != null)
                {
                    var sUi = this.WeighingUIBorder.Child as SimpleWeighingUc;
                    if (sUi == null)
                    {
                        //UI不对
                        this.WeighingUIBorder.Child = null;
                    }
                    else
                    {
                        //改变界面布局
                        sUi.ReLayout();
                    }
                }

                if (this.WeighingUIBorder.Child == null)
                {
                    this.WeighingUIBorder.Child = new SimpleWeighingUc();
                }
            }
        }

    }
}